package com.wlb365.financing.modules.trade.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlb365.financing.common.constants.ApiConstants;
import com.wlb365.financing.common.constants.SysConstant;
import com.wlb365.financing.common.dto.R;
import com.wlb365.financing.common.exception.AdminException;
import com.wlb365.financing.common.utils.JsonSchemaUtil;
import com.wlb365.financing.common.utils.ShiroUtil;
import com.wlb365.financing.common.utils.StringUtils;
import com.wlb365.financing.modules.esign.service.ESignService;
import com.wlb365.financing.modules.sys.entity.Dept;
import com.wlb365.financing.modules.sys.service.IDeptService;
import com.wlb365.financing.modules.sys.service.IDictService;
import com.wlb365.financing.modules.sys.service.IUserService;
import com.wlb365.financing.modules.trade.response.QueryBankListRes;
import com.wlb365.financing.modules.trade.response.QueryPageVoucherDTO;
import com.wlb365.financing.modules.trade.response.TradeProcessDataListResult;
import com.wlb365.financing.modules.trade.response.TradeQueryProcessDataDetailRes;
import com.wlb365.financing.modules.trade.response.VoucherDetailRes;
import com.wlb365.financing.modules.trade.response.VoucherPreviewRes;
import com.wlb365.financing.modules.trade.response.VoucherQueryRes;
import com.wlb365.financing.modules.trade.response.audit.AuditDto;
import com.wlb365.financing.modules.trade.response.audit.QueryAuditListResult;
import com.wlb365.financing.modules.trade.response.data.QuerySchemaByBtypeRes;
import com.wlb365.financing.modules.trade.response.voucher.VoucherUpdateRes;
import com.wlb365.financing.modules.trade.service.IAuditService;
import com.wlb365.financing.modules.trade.service.IDataService;
import com.wlb365.financing.modules.trade.service.IVoucherService;
import com.wlb365.financing.modules.trade.vo.VoucherQueryVO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 凭证管理类.
 *
 * @author zwh
 * @version 1.0
 */
@RestController
@RequestMapping("voucher")
public class VoucherController {
    @Autowired
    private IVoucherService voucherService;
    @Autowired
    private IDataService dataService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IDictService dictService;
    @Autowired
    private IAuditService auditService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ESignService eSignService;

    /**
    * 凭证列表页面.
    * @param
    * @author zwh
    * @return org.springframework.web.servlet.ModelAndView
    **/
    @RequiresPermissions("voucher:index")
    @GetMapping(value = "index")
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView("voucher/voucher.html");
        mv.addObject("supplierList", deptService.listDeptByType(SysConstant.DEPT_TYPE_0));
        mv.addObject("coreList", deptService.listDeptByType(SysConstant.DEPT_TYPE_1));
        mv.addObject("bankList", deptService.listDeptByType(SysConstant.DEPT_TYPE_2));
        mv.addObject("dictList", dictService.listAllDictItemByCode("VOUCHER"));
        return mv;
    }

    /**
    * 凭证列表数据.
    * @param queryVO
    * @author zwh
    * @return com.wlb365.financing.common.dto.R
    **/
    @GetMapping(value = "list/data")
    public R listData(VoucherQueryVO queryVO) {
        VoucherQueryRes res = voucherService.page(queryVO);

        Page<QueryPageVoucherDTO> page = new Page<>();
        page.setCurrent(res.getCurrent());
        page.setSize(res.getSize());
        page.setTotal(res.getTotal());
        page.setRecords(res.getItems());

        return R.ok(page);
    }

    /**
    * 获得凭证详情.
    * @param id
    * @author zwh
    * @return com.wlb365.financing.common.dto.R
    **/
    @GetMapping(value = "get")
    public R id(String id) {
        VoucherDetailRes res = voucherService.detail(id);
        JSONObject obj = JSONUtil.parseObj(res);
        obj.put("jsonData", JSONUtil.parseObj(res.getJsonData()));
        obj.put("uiSchema", JSONUtil.parseObj(res.getUiSchema()));
        return R.ok(obj);
    }

    /**
     * 确认签章.
     * @param id
     * @param flowId
     * @author zwh
     * @return com.wlb365.financing.common.dto.R
     **/
    @PostMapping(value = "confirmSign")
    public R confirmSign(String id, String flowId) {
        Integer signStatus = eSignService.getSignStatus(flowId, ShiroUtil.getUser().getAccountId());
        if (ApiConstants.SIGN_STATUS_2.equals(signStatus)) {
            VoucherUpdateRes res = voucherService.update(id, null,  String.valueOf(signStatus), true);
            return R.ok(res);
        }else if (ApiConstants.SIGN_STATUS_4.equals(signStatus)) {
            voucherService.update(id, null,  String.valueOf(signStatus), true);
            return R.fail("签署人拒绝签署");
        }else{
            return R.fail("签署人还未完成签署");
        }
    }

    /**
    * 更新凭证信息.
    * @param id 凭证id
    * @param bankId 银行id
    * @author zwh
    * @return com.wlb365.financing.common.dto.R
    **/
    @RequiresPermissions("voucher:generate")
    @PostMapping(value = "update")
    public R update(String id, String bankId) {
        return R.ok(voucherService.update(id, bankId, null, false));
    }

    /**
    * TODO 校验凭证，用于生成前校验.
    * @param tradeId
    * @param templateId
    * @author zwh
    * @return com.wlb365.financing.common.dto.R
    **/
    @RequiresPermissions("voucher:generate")
    @PostMapping(value = "generate/check")
    public R generateCheck(String tradeId, String templateId) {
        System.out.println(tradeId + ":" + templateId);
        return R.ok();
    }

    /**
    * 审核凭证.
    * @param id 凭证id
    * @param status 审核状态 1通过，2拒绝
    * @param remark 审核备注
    * @author zwh
    * @return com.wlb365.financing.common.dto.R
    **/
    @RequiresPermissions("voucher:audit")
    @PostMapping(value = "audit")
    public R audit(String id, String status, String remark) {
        return R.ok(voucherService.audit(id, status, remark));
    }

    /**
    * 撤销凭证.
    * @param id
    * @author zwh
    * @return com.wlb365.financing.common.dto.R
    **/
    @RequiresPermissions("voucher:cancel")
    @PostMapping(value = "cancel")
    public R cancel(String id) {
        return R.ok(voucherService.cancelVoucher(id));
    }

    /**
     * 查询审批记录.
     * @param id
     * @author zwh
     * @return com.wlb365.financing.common.dto.R
     **/
    @GetMapping(value = "audit/list/data")
    public R auditList(String id) {
        QueryAuditListResult result = auditService.list(id);
        if (result.getItems() != null) {
            result.getItems().forEach(auditDto -> {
                if (StringUtils.isNotEmpty(auditDto.getAuditBy())) {
                    auditDto.setName(userService.getById(auditDto.getAuditBy()).getRealname());
                }
            });
        }
        Page<AuditDto> page = new Page<>();
        page.setCurrent(1);
        page.setSize(result.getItems().size());
        page.setTotal(result.getItems().size());
        page.setRecords(result.getItems());
        return R.ok(page);
    }


}
